from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import F
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from commodity.models import Types, CommodityInfos

# Create your views here.

# def commodityView(request):
#     return HttpResponse('Hello World!')

def detailView(request, id):
    """
    商品详情页视图函数
    - 获取指定ID的商品详情
    - 获取销量前五的相关商品
    - 检查商品是否被当前用户收藏
    """
    title = '商品介绍'
    classContent = 'details'
    # 查询除了当前商品外的前五个商品（推荐商品）
    items = CommodityInfos.objects.exclude(id=id).order_by('-sold')[:5]
    # 查询指定ID的商品，如果没有就返回None
    commoditys = CommodityInfos.objects.filter(id=id).first()
    # 从Session中获取用户收藏列表
    likesList = request.session.get('likes', [])
    # 判断当前商品是否被用户收藏
    likes = True if id in likesList else False

    return render(request, 'details.html', locals())

# Create your views here.

def commodityView(request):

    title='商品列表'
    classContent='commoditys'
    firsts = Types.objects.values('firsts').distinct()
    typesList=Types.objects.all()

    t=request.GET.get('t','')
    s=request.GET.get('s','sold')
    p= request.GET.get('p', '1')
    n = request.GET.get('n', '')

    commodityInfos=CommodityInfos.objects.all()

    if t:
        types=Types.objects.filter(id=t).first()
        commodityInfos=commodityInfos.filter(types=types.seconds)
    if s:
        commodityInfos = commodityInfos.order_by('-' + s)
    if n:
        commodityInfos = commodityInfos.filter(name__contains=n)

    paginator = Paginator(commodityInfos, 6)
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)

    return render(request, 'commodity.html', locals())

# def detailView(request):
#     return HttpResponse('Hello World!')
def collectView(request):

    # 处理收藏请求，更新收藏数量，记录收藏状态
    id = request.GET.get('id','')
    result={"result":"已收藏"}
    likes=request.session.get('likes', [])

    #如果id不为空且变量id不在likes里，程序执行收藏
    if id and not int(id) in likes:
        CommodityInfos.objects.filter(id=id).update(likes=F('likes')+1)
        result["result"]="收藏成功"
        request.session['likes'] = likes +[int(id)]
    return JsonResponse(result)
